package com.stone.sys.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.stone.para.IConstant;
import com.stone.sys.pojo.TOrgan;
import com.stone.sys.pojo.TUser;
import com.stone.sys.service.OrganService;
import com.stone.sys.service.UserService;
import com.stone.utils.JsonUtils;
import com.stone.utils.Resources;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;
import frm.ssh.util.SpringUtil;

/**
 * 登陆用ACTION
 * 
 * <pre>
 * @author：JZ
 * @since:2010/02/10
 * </pre>
 */
public class LoginAction extends BaseAction {

	private UserService userService;
	private String loginId;
	private String password;
	private String err = "";
	// 父节点
	private String parentID;
	
	/**
	 * 登录验证
	 */
	public String login() throws AppException {

		TUser user = null;

		List<HashMap<String, Object>> list = userService.getListByDHql(" u as u", "loginId = ?", new Object[]{loginId}, "", "TUser u");

		if (list.size() == 0) {
			this.err = "没有此用户";
		} else {
			user = (TUser) ((HashMap<String, Object>)list.get(0)).get("u");
			if (!password.equals(user.getPassword())) {
				this.err = "用户密码错误";
			}
			
			if ("0".equals(user.getState()) && !"1".equals(user.getIsadmin())) {
				this.err = "该用户已停用";
			}
		}

		if (!err.equals("")) {
			
			userList  = this.userService.getListByDHql("u.loginId as loginId, u.name as name", 
					"",
					null, 
					" order by u.id", 
					"TUser u");
			
			return "LOGIN_ERROR";
		} else {
			
			// 是否管理员（1是,0不是）
			this.setSessionAttribute(IConstant.SESSION_ISADMIN, user.getIsadmin());

			// 用户信息放入SESSION
			this.setSessionAttribute(IConstant.SESSION_TUSER, user);
			
			// 角色串
			String sql = "Select Substr(Sys_Connect_By_Path(NAMEEN, ','), 2) as v " + 
			  "From (Select Rownum Rid, Rownum + 1 Next_Rid, NAMEEN " + 
			          "From sys_role " + 
			         "where id in (select role_id from sys_user_role where user_id = '" + user.getId() + "')) " + 
			 "Where Rid = " + 
			       "(Select Count(*) " + 
			          "From sys_role " + 
			         "where id in (select role_id from sys_user_role where user_id = '" + user.getId() + "')) " + 
			 "Start With Rid = 1 " + 
			 "Connect By Prior Next_Rid = Rid ";

			String roles = "";
			List<HashMap<String, Object>> l = userService.findListBySql(sql);

			if (l.size() > 0) {

				roles = l.get(0).get("v").toString() + ",";
			} else {
				roles = "";
			}
			
			if ("1".equals(user.getIsadmin())) {
				roles += "isadmin,";
			}
			
			// 角色传放入SESSION
			this.setSessionAttribute(IConstant.SESSION_ROLES, roles);
			
			// 机构信息
			if (user.getOrgan().getId() != 0) {
	
				TOrgan organ = (TOrgan)this.userService.findById(user.getOrgan().getId(), TOrgan.class.getName());
				
				if (organ != null && organ.getOrganCode() != null) {
					
					this.setSessionAttribute(IConstant.SESSION_TORGAN, organ);
					this.setSessionAttribute(IConstant.SESSION_TORGAN_CODE, organ.getOrganCode());
					this.setSessionAttribute(IConstant.SESSION_ISCITY, organ.getOrganCode().toString().length() == 9 ? "0" : "1");
					
				} else  {
					this.err = "该用户没有上级部门，没有权限查询";
					return "LOGIN_ERROR";
				}
			} else {
				
				this.setSessionAttribute(IConstant.SESSION_TORGAN_CODE,Long.parseLong("101"));
			}

			return SUCCESS;
		}
	}
	
	/**
	 * 查询登陆用户权限对应的菜单
	 * @return
	 * @throws AppException
	 */	
	@SuppressWarnings("unchecked")
	public void getMenuByUserRole() throws IOException, AppException {
		
		List<HashMap<String,Object>> listTree = null;
		TOrgan o  = (TOrgan)super.getSession().getAttribute(IConstant.SESSION_TORGAN);
		TUser loginUser  = (TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER);//系统当前登录用户
		int grjhCount=0;
		String grsql="select plan.id from tab_plan plan where to_char(SYSDATE+7, 'yyyy-mm-dd') BETWEEN to_char(startdate-3, 'yyyy-mm-dd') AND to_char(enddate+7, 'yyyy-mm-dd')"+
		" AND (plan.responsible = '"+loginUser.getName()+ "'  or plan.id in (select t.planid from TAB_PLAN_BZ t where t.planid= plan.id and delflag='0' and t.cyname like '%"+((TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER)).getName()+ "%'))";
		int grgdCount=0;
		String grgdsql="select s.id from TAB_GZRWD s  where s.state =0 and (s.zbzname = '"+loginUser.getName()+ "'  or  s.zbyname like '%"+loginUser.getName()+ "%')";
		int grglbzCount=0;//管理工作[班组]
		String grglbzsql="select s.id from TAB_PLAN_WEEK_DETAIL s  where wcqk is null and fzrname  like '%"+loginUser.getName()+ "%' and plantype = 2";
		
		grjhCount=this.getCount(grsql);
		grgdCount=this.getCount(grgdsql);
		grglbzCount=this.getCount(grglbzsql);
		//班组代办事项
		int bzjhCount=0;
		String bzjhsql="select plan.id from tab_plan plan where "+
		"  (plan.phbz = '"+o.getId()+ "'  and plan.id in (select t.planid from TAB_PLAN_BZ t where t.planid= plan.id and t.bzid= plan.phbz and (t.cyname is null or t.fzrname is null)))" ;
		int bzglgqCount=0;//管理工作[工区]
		//String bzglgqsql="select s.id from TAB_PLAN_WEEK_DETAIL s  where wcqk is null and fzrname  like '%"+loginUser.getName()+ "%' and plantype = 1";
		String bzglgqsql="select s.id from TAB_PLAN_WEEK_DETAIL s  where sjwcdate is null and bz like '%"+loginUser.getOrgan().getId()+ "%' and plantype = 1";
		int bzqxCount=0;//设备缺陷(等待计划)
		String bzqxsql="select s.cid from dm_defect s  where (notify_department = 1 or notify_department1 = 1) and (status = 'Q02' or status = 'Q01' or status = 'Q03') and (flag <> '1' or flag is null) ";
		
		bzjhCount=this.getCount(bzjhsql);
		bzglgqCount=this.getCount(bzglgqsql);
		bzqxCount=this.getCount(bzqxsql);
		
		int xqqxCount=0;//by wangtao add 20121114生产管理设备缺陷消缺计划
		String xqqxsql="select a.cid from dm_defect a,TAB_SBQXJL s  where  a.cid = s.defectid and state = '1' ";
		xqqxCount=this.getCount(xqqxsql);
		
		int yxqqxCount=0;//by wangtao add 20121114生产管理设备缺陷已消除缺陷数
		String yxqqxsql="select a.cid from dm_defect a,TAB_SBQXJL s  where  a.cid = s.defectid and state = '2' ";
		yxqqxCount=this.getCount(yxqqxsql);
		// 如果是超级管理员具有全部权限
		/*if ("1".equals(this.getSessionAttribute(IConstant.SESSION_ISADMIN))) {
			
			listTree = userService.getListByDHql(
					"m.id as id, m.title as text, m.qtip as qtip,m.url as url,m.parentID as parentID," +
					"(case when (select count(tm.id) from TMenu tm where tm.parentID = m.id and tm.btnId is null)> 0 then false else true end) as leaf", 
					"m.parentID = ? and m.btnId is null ",
					new Object[]{Long.parseLong(parentID)}, 
					"order by m.parentID,m.sortId",
					"TMenu m");
		} else {*/
		
			/*listTree  = userService.getListByDHql(
					"m.id as id, m.title as text, m.qtip as qtip,m.url as url,m.parentID as parentID," +
					"(case when (select count(tm.id) from TMenu tm where tm.parentID = m.id and tm.btnId is null)> 0 then false else true end) as leaf", 
					"u.id = ur.userId and ur.roleId = rm.roleId and rm.menuId = m.id and m.parentID = ? and u.id = ? and m.btnId is null ",
					new Object[]{Long.parseLong(parentID),((TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER)).getId()}, 
					" group by m.id,m.title,m.url,m.qtip,m.parentID,m.sortId order by m.parentID,m.sortId",
					" TUser u, TUserRole ur, TRoleMenu rm ,TMenu m");*/
			String sql="select m.id as id, (case m.id when 3720 then CONCAT(m.title,'【"+grjhCount+"】') when 3727 then CONCAT(m.title,'【"+grgdCount+"】') when 3732 then CONCAT(m.title,'【"+grglbzCount+"】') when 3729 then CONCAT(m.title,'【"+bzjhCount+"】') when 3730 then CONCAT(m.title,'【"+bzglgqCount+"】') when 3731 then CONCAT(m.title,'【"+bzqxCount+"】') when 3506 then CONCAT(m.title,'【"+bzqxCount+"】') when 3507 then CONCAT(m.title,'【"+xqqxCount+"】') when 3508 then CONCAT(m.title,'【"+yxqqxCount+"】') else m.title end) as text, m.qtip as qtip,m.url as url,m.PARENT_ID as parentID," +
					"(case when (select count(tm.id) from SYS_MENU tm where tm.PARENT_ID = m.id and tm.BTN_ID is null)> 0 then 0 else 1 end) as leaf"+
					" from SYS_USER u, SYS_USER_ROLE ur, SYS_ROLE_MENU rm ,SYS_MENU m"+
					" where u.id = ur.USER_ID and ur.ROLE_ID = rm.ROLE_ID and rm.MENU_ID = m.id and m.PARENT_ID ="+Long.parseLong(parentID)+"  and u.id ="+((TUser)super.getSession().getAttribute(IConstant.SESSION_TUSER)).getId()+" and m.BTN_ID is null "+
					" group by m.id,m.title,m.url,m.qtip,m.PARENT_ID,m.SORT_ID order by m.PARENT_ID,m.SORT_ID";
					 
			listTree  = userService.findListBySql(sql);
		//	}
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
        JSON json = JSONSerializer.toJSON(listTree, jsonConfig);
        super.getResponse().getWriter().print(json.toString());
        
	}

	/**
	 * 登陆页面的下拉框
	 * 
	 * @return
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public String beforeLogin() throws Exception {

		userList  = this.userService.getListByDHql("u.loginId as loginId, u.name as name", 
																				"",
																				null, 
																				" order by u.sortid", 
																				"TUser u");
		return "LOGIN_ERROR";
		
	}
	/**
	 * 登录验证从外网登陆
	 */
	public String loginEx() throws AppException {

		TUser user = null;

		List<HashMap<String, Object>> list = userService.getListByDHql(" u as u", "loginId = ?", new Object[]{loginId}, "", "TUser u");

		if (list.size() == 0) {
			this.err = "没有此用户";
		} else {
			user = (TUser) ((HashMap<String, Object>)list.get(0)).get("u");
			if (!password.equals(user.getPassword())) {
				this.err = "用户密码错误";
			}
			
			if ("0".equals(user.getState()) && !"1".equals(user.getIsadmin())) {
				this.err = "该用户已停用";
			}
		}

		if (!err.equals("")) {
			
			userList  = this.userService.getListByDHql("u.loginId as loginId, u.name as name", 
					"",
					null, 
					" order by u.id", 
					"TUser u");
			
			return "LOGIN_ERROR";
		} else {
			
			// 是否管理员（1是,0不是）
			this.setSessionAttribute(IConstant.SESSION_ISADMIN, user.getIsadmin());

			// 用户信息放入SESSION
			this.setSessionAttribute(IConstant.SESSION_TUSER, user);
			
			// 角色串
			String sql = "Select Substr(Sys_Connect_By_Path(NAMEEN, ','), 2) as v " + 
			  "From (Select Rownum Rid, Rownum + 1 Next_Rid, NAMEEN " + 
			          "From sys_role " + 
			         "where id in (select role_id from sys_user_role where user_id = '" + user.getId() + "')) " + 
			 "Where Rid = " + 
			       "(Select Count(*) " + 
			          "From sys_role " + 
			         "where id in (select role_id from sys_user_role where user_id = '" + user.getId() + "')) " + 
			 "Start With Rid = 1 " + 
			 "Connect By Prior Next_Rid = Rid ";

			String roles = "";
			List<HashMap<String, Object>> l = userService.findListBySql(sql);

			if (l.size() > 0) {

				roles = l.get(0).get("v").toString() + ",";
			} else {
				roles = "";
			}
			
			if ("1".equals(user.getIsadmin())) {
				roles += "isadmin,";
			}
			
			// 角色传放入SESSION
			this.setSessionAttribute(IConstant.SESSION_ROLES, roles);
			
			// 机构信息
			if (user.getOrgan().getId() != 0) {
	
				TOrgan organ = (TOrgan)this.userService.findById(user.getOrgan().getId(), TOrgan.class.getName());
				
				if (organ != null && organ.getOrganCode() != null) {
					
					this.setSessionAttribute(IConstant.SESSION_TORGAN, organ);
					this.setSessionAttribute(IConstant.SESSION_TORGAN_CODE, organ.getOrganCode());
					this.setSessionAttribute(IConstant.SESSION_ISCITY, organ.getOrganCode().toString().length() == 9 ? "0" : "1");
					
				} else  {
					this.err = "该用户没有上级部门，没有权限查询";
					return "LOGIN_ERROR";
				}
			} else {
				
				this.setSessionAttribute(IConstant.SESSION_TORGAN_CODE,Long.parseLong("101"));
			}

			return SUCCESS;
		}
	}
	private int getCount(String sql){
		int count = 0;
		List templist = null;
		templist = userService.findListBySql(sql);
		if(templist != null){
			count = templist.size();
		}
		return count;
	}
	private List<HashMap<String,Object>> userList;
	
	private List<HashMap<String,Object>> deptList;
	
	public List<HashMap<String, Object>> getUserList() {
		return userList;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getLoginId() {
		return loginId;
	}

	public void setLoginId(String loginId) {
		this.loginId = loginId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getErr() {
		return err;
	}

	public String getParentID() {
		return parentID;
	}

	public void setParentID(String parentID) {
		this.parentID = parentID;
	}

	public void setErr(String err) {
		this.err = err;
	}

	public List<HashMap<String, Object>> getDeptList() {
		return deptList;
	}
	
	
	
}
